package chixing.day14.work;

import java.util.ArrayList;
import java.util.List;

public class Cart{ // 容器
    private List<Product> productList; // 声明变量


    // 构造函数的作用 ： 初始化对象（初始化购物车）
    public Cart(){
        productList = new ArrayList<>();
    }

    // 增加
    public void add(Product product){
        productList.add(product);
        System.out.println("添加成功！");
    }

    //根据下标获得
    public Product get(int index){
        return productList.get(index);
    }
    //根据商品名称获得
    public Product get(String productName){
        for (Product product : productList) {
            if (product.getName().equals(productName)) {
                return product;
            }
        }
        return null;
    }
    //删除
    public Product remove(int index){
        return productList.remove(index);
    }

    //遍历然后输出总价值
    public void display(){
        double totalPrice = 0;
        for (Product product : productList) {
            totalPrice += product.getPrice();
            System.out.println(product);
        }
        System.out.println("总价为：" + totalPrice);

    }
    public static void main(String[] args) {
        Cart cart = new Cart();
        cart.add(new Product("电脑", 5000, 0));
        cart.add(new Product("鼠标", 20, 1));
        cart.add(new Product("键盘", 500, 2));
        cart.add(new Product("手机", 2000, 3));
        cart.add(new Product("鼠标垫", 10, 4));
        cart.add(new Product("硬盘", 700, 5));
        cart.add(new Product("内存", 700, 6));
        cart.add(new Product("显示器", 1999, 7));
        cart.add(new Product("主板", 2000, 8));
        cart.add(new Product("显卡", 20000, 9));
        //cart.display();
        System.out.println(cart.get(0));
        System.out.println("--------------------");
        System.out.println(cart.get("鼠标"));
        System.out.println("--------------------");
        System.out.println(cart.remove(3));
        System.out.println("--------------------");
        cart.display();
    }

}
